//package com.cjl.open.retrofit.download;
//
//import io.reactivex.Observer;
//import io.reactivex.disposables.Disposable;
//import io.reactivex.schedulers.Schedulers;
//import okhttp3.*;
//import okhttp3.logging.HttpLoggingInterceptor;
//import org.jetbrains.annotations.NotNull;
//import retrofit2.Retrofit;
//import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
//import retrofit2.converter.gson.GsonConverterFactory;
//
//import java.io.File;
//import java.io.IOException;
//import java.io.RandomAccessFile;
//import java.util.Objects;
//import java.util.concurrent.TimeUnit;
//
//public class DownLoadDemo {
//    public static void main(String[] args) {
//        download("imgs/materials/2021/9/14/20210914104451_38a62c47abff9c9c637e6bd220e182ff.mp4", "/home/battlecall/tmp/y.mp4", new DownloadCallback() {
//            @Override
//            public void onStart(Disposable d) {
//
//            }
//
//            @Override
//            public void onProgress(long totalBytes, long currentBytes, int progress) {
//                System.out.println("y DownloadCallback totalBytes = " + totalBytes + ", currentBytes = " + currentBytes + ", progress = " + progress);
//
//            }
//
//            @Override
//            public void onFinish(File file) {
//
//            }
//
//            @Override
//            public void onError(String msg) {
//
//            }
//        });
//        download("imgs/materials/2021/8/24/20210824094931_c973f2561e3da55cd14b3702271b1b34.mp4", "/home/battlecall/tmp/z.mp4", new DownloadCallback() {
//            @Override
//            public void onStart(Disposable d) {
//                System.out.println("DownLoadDemo.onStart DownloadCallback ");
//            }
//
//            @Override
//            public void onProgress(long totalBytes, long currentBytes, int progress) {
//                System.out.println("z DownloadCallback totalBytes = " + totalBytes + ", currentBytes = " + currentBytes + ", progress = " + progress);
//            }
//
//            @Override
//            public void onFinish(File file) {
//                System.out.println("DownLoadDemo.onFinish DownloadCallback "+file.getAbsolutePath());
//            }
//
//            @Override
//            public void onError(String msg) {
//                System.out.println("DownLoadDemo.onError DownloadCallback error:"+msg);
//            }
//        });
//
//    }
//
//    public static void download(String url,String filePath,DownloadCallback callback){
//        System.out.println("DownLoadDemo.download");
//        if (Objects.isNull(url) || Objects.isNull(filePath) || url.isEmpty() || filePath.isEmpty()) {
//            if (null != callback) {
//                callback.onError("url or path empty");
//            }
//            return;
//        }
//        File oldFile = new File(filePath);
//        if (oldFile.exists()) {
//            if (null != callback) {
//                callback.onFinish(oldFile);
//            }
//            return;
//        }
//        DownLoadListener downLoadListener = new DownLoadListener() {
//            @Override
//            public void onStart(ResponseBody responseBody) {
//                saveFile(responseBody,url,filePath,callback);
//            }
//        };
//
//        downloadFile(url, CommonUtils.getTempFile(url, filePath).length(), downLoadListener, new Observer<ResponseBody>() {
//            public void onSubscribe( Disposable d) {
//                System.out.println("DownLoadDemo.onSubscribe");
//                if (callback != null){
//                    callback.onStart(d);
//                }
//            }
//
//            @Override
//            public void onNext( ResponseBody responseBody) {
//                System.out.println("DownLoadDemo.onNext");
//            }
//
//            @Override
//            public void onError(Throwable e) {
//                System.out.println("DownLoadDemo.onError");
//                if (null != callback) {
//                    callback.onError(e.getMessage());
//                }
//            }
//
//            @Override
//            public void onComplete() {
//                System.out.println("DownLoadDemo.onComplete");
//
//            }
//
//        });
//
//
//
//    }
//
//    private static void saveFile(ResponseBody responseBody, String url, String filePath, DownloadCallback callback) {
//        File tempFile = CommonUtils.getTempFile(url, filePath);
//        try {
//            writeFileToDisk(responseBody, tempFile.getAbsolutePath(), callback);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return;
//        }
//        boolean renameSuccess = tempFile.renameTo(new File(filePath));
//        if (renameSuccess && callback != null) {
//            callback.onFinish(new File(filePath));
//        }
//
//
//    }
//
//    private static void writeFileToDisk(ResponseBody responseBody, String filePath, DownloadCallback callback) throws Exception{
//        long totalByte = responseBody.contentLength();
//        long downloadByte = 0;
//        File file = new File(filePath);
//        if (!file.getParentFile().exists()) {
//            file.getParentFile().mkdirs();
//        }
//
//        byte[] buffer = new byte[1024 * 4];
//        RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rwd");
//        long tempFileLen = file.length();
//        randomAccessFile.seek(tempFileLen);
//        while (true) {
//            int len = responseBody.byteStream().read(buffer);
//            if (len == -1) {
//                break;
//            }
//            randomAccessFile.write(buffer, 0, len);
//            downloadByte += len;
//            callback.onProgress(tempFileLen + totalByte, tempFileLen + downloadByte, (int) ((downloadByte * 100) / totalByte));
//        }
//        randomAccessFile.close();
//    }
//
//    public static void downloadFile(String url, long startPos, DownLoadListener listener, Observer<ResponseBody> observer){
//        System.out.println("DownLoadDemo.downloadFile");
//        OkHttpClient client = new OkHttpClient.Builder()
//                .connectTimeout(15, TimeUnit.SECONDS)
//                .readTimeout(15, TimeUnit.SECONDS)
//                .writeTimeout(15, TimeUnit.SECONDS)
//                .addInterceptor(new Interceptor() {
//                    @NotNull
//                    @Override
//                    public Response intercept(@NotNull Chain chain) throws IOException {
//                        Request originalRequest = chain.request();
//                        return chain.proceed(originalRequest.newBuilder()
//                                .addHeader("Accept-Encoding", "gzip")
////                                .method(originalRequest.method(),originalRequest.body())
//                                .build());
//                    }
//                })
//                .addInterceptor(new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
//                    @Override
//                    public void log(String message) {
//                        System.out.println("DownLoadDemo.log "+message);
//                    }
//                }))
//                .addInterceptor(new DownloadInterceptor(listener))
//                .build();
//
//        Retrofit retrofit = new Retrofit.Builder()
//                .baseUrl("http://asimgs.cp61.ott.cibntv.net/")
//                .addConverterFactory(GsonConverterFactory.create())
//                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
//                .client(client)
//                .build();
//        retrofit.create(Mp4Res.class).downloadFile("bytes=" + startPos + "-", url)
////                .subscribeOn(Schedulers.io())
//                .subscribe(observer);
//    }
//}
